﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Threading;

using NetworkServices;
using SearchRS;


namespace SearchRS
{
    public class HoradotSearcher : RSSearcher
    {
        private static SearchRS m_searchRS;
        private static ManualResetEvent m_shouldStopEvent;

        public HoradotSearcher(SearchRS searchRS, ManualResetEvent shouldStopEvent)
        {
            m_searchRS = searchRS;
            m_shouldStopEvent = shouldStopEvent;
        }

        public void Search(string searchString)
        {
            string s = System.Web.HttpUtility.UrlEncode(searchString, System.Text.Encoding.GetEncoding("windows-1255"));

            for (int i = 1; i < 11; i++)
            {
                string searchLink = "http://www.horadot.net/search," + s + ",0," + i + ".html";

                AsyncWebRequest request = new AsyncWebRequest();
                request.SendWebBBRequest(searchLink, "", "", 3, "", false, "", m_shouldStopEvent, 0, "", true,
                             SearchHoardotCB, searchString);

                Thread.Sleep(300);
            }
        }

        private static void SearchHoardotCB(string buffer, HttpWebResponse respObj, string searchCookieParam, object userState)
        {
            if (buffer == null || buffer.Contains("לא נמצאו תוצאות"))
            {
                return;
            }

            string searchString = (string)userState;

//          <a href="view,30338,שאטר_איילנד_-_Shutter_Island_[תרגום_מובנה]_[1080p_Bluray_DTS]_.html"><font color=darkblue><b>
//          <span style="font-size: 12pt;" lang="he">שאטר איילנד / Shutter Island [תרגום מובנה] [1080p Bluray DTS] </span></b></font></a>

            Regex re = new Regex("a href=\"([^\"]+)\"(.+?)</a>", RegexOptions.Singleline);
            MatchCollection matches = re.Matches(buffer);
            foreach (Match m in matches)
            {
                string link = m.Groups[1].Value;
                string title = Utils.Utils.CleanName(m.Groups[2].Value);
                title = title.Replace("</font>", "").Replace("</b>", "").Replace("</span>", "");
                title = title.Substring(title.LastIndexOf(">")+1).Trim();

                if (Utils.Utils.AllWordsIncluded(title, searchString))
                {
                    if (title.Contains("תרגום מובנה"))
                    {
                        AsyncWebRequest request = new AsyncWebRequest();
                        link = "http://www.horadot.net/" + link;
                        request.SendWebBBRequest(link, "", "", 3, "", false, "", m_shouldStopEvent, 0, "", true,
                                     CollectHoradotLinkCB, new string[] { title, link });
                    }
                }
            }
        }

        private static void CollectHoradotLinkCB(string buffer, HttpWebResponse respObj, string searchCookieParam, object userState)
        {

            if (buffer == null)
                return;

            List<string> links = new List<string>();
            string[] ctx = (string[])userState;
            string title = (string)ctx[0];
            string link = (string)ctx[1];

            Regex re = new Regex("http://www.filesonic.com/[^']+'");

            MatchCollection matches = re.Matches(buffer);
            foreach (Match m in matches)
            {
                links.Add(m.Groups[0].Value);
            }

            if (links.Count > 0)
            {
                List<string> cleanedLinks = m_searchRS.CleanLinks(links.ToArray());

                if (cleanedLinks.Count > 0)
                {
                    title = Utils.Utils.CleanName(title);
                    m_searchRS.AddResult(title, link, cleanedLinks, "", "", ResultState.Verified);
                }
            }
        }



    }
}
